<template>
  <div v-if="pageShow" v-loading="loading">
    <div class="bread-box but20">
      <el-breadcrumb separator-class="el-icon-arrow-right">
        <el-breadcrumb-item class="btn-green" style=" color: #3DC094;" @click.native="goBack">门店建设</el-breadcrumb-item>
        <el-breadcrumb-item> {{ typeFlag === 'edit' ? '编辑': '新增' }}</el-breadcrumb-item>
      </el-breadcrumb>
      <div>
        <el-button type="primary" size="mini" @click.native="submitForm('save')">保存</el-button>
        <el-button size="mini" @click.native="goBack">返回</el-button>
      </div>
    </div>
    <div class="mt20">
      <div class="qup-title-box">
        <span class="border" /><span>新增门店建设</span>
      </div>
      <el-form ref="refForm" :rules="formRules" :model="formData" size="mini" label-width="120px">
        <el-row class="form_item_height">
          <el-col :xs="12" :sm="12" :md="8" :lg="6" :xl="6">
            <el-form-item label="门店建设范围:" prop="selectRange" required>
              <!-- <template> -->
              <el-checkbox-group v-model="formData.selectRange" @change="handleCheckAllChange">
                <el-checkbox v-for="item in decorationRangeList" :key="item.dictCode" :label="item.dictCode">{{ item.dictName }}</el-checkbox>
              </el-checkbox-group>
              <!-- </template> -->

            </el-form-item>
          </el-col>
          <el-col :xs="12" :sm="12" :md="8" :lg="6" :xl="6">
            <el-form-item label="申请类别:" prop="applyCategory">
              <!-- <span>{{ formData.applyCategory }}</span> -->
              <el-select
                v-model="formData.applyCategory"
                placeholder="请选择"
                style="width: 100%"
                disabled
              >
                <el-option
                  v-for="item in applyCategoryList"
                  :key="item.dictCode"
                  :label="item.dictName"
                  :value="item.dictCode"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :xs="12" :sm="12" :md="8" :lg="6" :xl="6">
            <el-form-item label="门店:" prop="shop">
              <input-with-dialog
                v-model="formData.shop"
                :props="{label:'name',value:'code'}"
                :multiple="false"
                :focus-query="true"
                :config="shopDialogConfig"
                @change="handleChangeShop"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :xs="12" :sm="12" :md="8" :lg="6" :xl="6">
            <el-form-item label="门店编码:" prop="shopCode">
              <span>{{ formData.shopCode }}</span>
            </el-form-item>
          </el-col>
          <el-col :xs="12" :sm="12" :md="8" :lg="6" :xl="6">
            <el-form-item label="门店建设项目号:" prop="constCode">
              <span>{{ formData.constCode }}</span>
            </el-form-item>
          </el-col>
          <el-col :xs="12" :sm="12" :md="8" :lg="6" :xl="6">
            <el-form-item label="所属客户编码:" prop="clientCode">
              <span>{{ formData.clientCode }}</span>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :xs="12" :sm="12" :md="8" :lg="6" :xl="6">
            <el-form-item label="所属客户名称:" prop="clientName">
              <span>{{ formData.clientName }}</span>
            </el-form-item>
          </el-col>
          <el-col :xs="12" :sm="12" :md="8" :lg="6" :xl="6">
            <el-form-item label="所属办事处:" prop="officeName">
              <span>{{ formData.officeName }}</span>
            </el-form-item>
          </el-col>
          <el-col :xs="12" :sm="12" :md="8" :lg="6" :xl="6">
            <el-form-item label="门店类型:" prop="shopType">
              <span>{{ formaterData(shopTypeList, formData.shopType) }}</span>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :xs="12" :sm="12" :md="8" :lg="6" :xl="6">
            <el-form-item label="门店业务类型:" prop="shopBizType">
              <span>{{ formaterArr(bizTypeList, formData.shopBizType) }}</span>
            </el-form-item>
          </el-col>
          <el-col :xs="12" :sm="12" :md="8" :lg="6" :xl="6">
            <el-form-item label="门店城市级别:" prop="shopCityLevel">
              <span>{{ formaterData(cityLevelList, formData.shopCityLevel) }}</span>
            </el-form-item>
          </el-col>
          <el-col :xs="12" :sm="12" :md="8" :lg="6" :xl="6">
            <el-form-item label="门店营业状态:" prop="businessStatus">
              <span>{{ formaterData(businessStatusList, formData.businessStatus) }}</span>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col>
            <el-form-item label="门店详细地址:" prop="shopAddress">
              <span>{{ formData.shopAddress }}</span>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :xs="12" :sm="12" :md="8" :lg="6" :xl="6">
            <el-form-item label="报图类型:" prop="marketType">
              <el-select
                v-model="formData.marketType"
                placeholder="请选择"
                style="width: 100%"
                :disabled="disabled"
                @change="changeMarketType"
              >
                <el-option
                  v-for="item in marketTypeList"
                  :key="item.dictCode"
                  :label="item.dictName"
                  :value="item.dictCode"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :xs="12" :sm="12" :md="8" :lg="6" :xl="6">
            <el-form-item label="门店建设类型:" prop="constType">
              <el-select
                v-model="formData.constType"
                placeholder="请选择"
                style="width: 100%"
                :disabled="disabled"
                @change="changeConstType"
              >
                <el-option
                  v-for="item in typeList"
                  :key="item.dictCode"
                  :label="item.dictName"
                  :value="item.dictCode"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :xs="12" :sm="12" :md="8" :lg="6" :xl="6">
            <el-form-item label="商家类别:" prop="bizmanType" :rules="[{ required: formData.marketType === 'NEW_MARKET', message: '请选择商家类别' }]">
              <el-select
                v-model="formData.bizmanType"
                placeholder="请选择"
                style="width: 100%"
                :disabled="disabled"
                @change="changeBizmanType"
              >
                <el-option
                  v-for="item in bizmanTypeList"
                  :key="item.dictCode"
                  :label="item.dictName"
                  :value="item.dictCode"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :xs="12" :sm="12" :md="8" :lg="6" :xl="6">
            <el-form-item label="装修形式:" prop="selectDecorationForm">
              <el-select
                v-model="formData.selectDecorationForm"
                multiple
                placeholder="请选择"
                style="width: 100%"
                :disabled="disabled || onlyStore"
                @change="changeDecorationForm"
              >
                <el-option
                  v-for="item in decorationFormList"
                  :key="item.dictCode"
                  :label="item.dictName"
                  :value="item.dictCode"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>
    <!-- -----------------测绘申请 -->
    <div v-if="hasMarket" class="mt20">
      <div class="qup-title-box">
        <span class="border" /><span>测绘申请</span>
      </div>
      <el-form ref="surveyForm" :model="formData.shopSurveyDTO" :validate-on-rule-change="false" :rules="formRules" size="mini" label-width="150px">
        <el-row class="form_item_height">
          <el-col v-if="hasDoor" :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
            <el-form-item label="测绘申请门头面积:" prop="applyDheadArea" :rules="[{ required: hasDoor, message: '请输入测绘申请门头面积' }]">
              <el-input v-model.number="formData.shopSurveyDTO.applyDheadArea" maxlength="130" />
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
            <el-form-item label="测绘申请卖场总面积:" prop="applyShopTotalArea" required>
              <el-input v-model.number="formData.shopSurveyDTO.applyShopTotalArea" maxlength="130" />
            </el-form-item>
          </el-col>
          <!-- <el-col :xs="12" :sm="12" :md="8" :lg="6" :xl="6">
            <el-form-item label="测绘申请卖场总面积:" prop="modifName" required>
              <el-input v-model="formData.shopSurveyDTO" maxlength="130" />
            </el-form-item>
          </el-col> -->
          <el-col v-if="hasRenovate" :xs="12" :sm="12" :md="8" :lg="6" :xl="6">
            <el-form-item label="翻新面积:" prop="refurbishArea" :rules="[{ required: hasRenovate, message: '请输入翻新面积' }]">
              <el-input v-model.number="formData.shopSurveyDTO.refurbishArea" maxlength="130" />
            </el-form-item>
          </el-col>
          <el-col v-if="hasExtend" :xs="12" :sm="12" :md="8" :lg="6" :xl="6">
            <el-form-item label="扩建面积:" prop="expansionArea" :rules="[{ required: hasExtend, message: '请输入扩建面积' }]">
              <el-input v-model.number="formData.shopSurveyDTO.expansionArea" maxlength="30" />
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
            <el-form-item label="预计报图区域:" prop="reportPicZoneArr">
              <!-- <el-select
                v-model="formData.shopSurveyDTO.reportPicZone"
                multiple
                placeholder="请选择"
                style="width: 100%"
                @change="handleChange"
              >
                <el-option
                  v-for="item in expectPicTypeList"
                  :key="item.dictCode"
                  :label="item.dictName"
                  :value="item.dictCode"
                />
              </el-select> -->
              <input-with-dialog
                v-model="formData.shopSurveyDTO.reportPicZoneArr"
                :props="{label:'areaName',value:'areaCode'}"
                :multiple="true"
                :config="areaConfig"
                @change="areaChange"
              />
            </el-form-item>
          </el-col>
          <el-col :xs="12" :sm="12" :md="8" :lg="6" :xl="6" required>
            <el-form-item label="卖场是否已拆除:" prop="isShopRemove">
              <el-select
                v-model="formData.shopSurveyDTO.isShopRemove"
                placeholder="请选择"
                style="width: 100%"
                @change="changeShopRemove"
              >
                <el-option
                  v-for="item in booleansIntList"
                  :key="item.dictCode"
                  :label="item.dictName"
                  :value="item.dictCode"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col v-if="formData.shopSurveyDTO.isShopRemove === 0" :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
            <el-form-item label="卖场未拆除原因:" prop="unremoveReason" :rules="[{ required: formData.shopSurveyDTO.isShopRemove === 0, message: '请输入卖场未拆除原因' }]">
              <el-input v-model="formData.shopSurveyDTO.unremoveReason" maxlength="300" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="测绘申请说明:" prop="applyDesc">
              <el-input v-model="formData.shopSurveyDTO.applyDesc" maxlength="1000" show-word-limit type="textarea" />
            </el-form-item>
          </el-col>
          <el-col :xs="12" :sm="12" :md="8" :lg="6" :xl="6">
            <el-form-item label="测绘申请人:" prop="applicantName">
              {{ formData.shopSurveyDTO.applicantName }}
            </el-form-item>
          </el-col>
          <el-col :xs="12" :sm="12" :md="8" :lg="6" :xl="6">
            <el-form-item label="测绘申请时间:" prop="applyTime">
              {{ formData.shopSurveyDTO.applyTime }}
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
            <el-form-item label="附件上传:" prop="modifName">
              <div v-for="item in fileTypeList" :key="item.id">
                <div class="qup-title-box">
                  <span class="border" /><span>附件上传-{{ item.attachmentType }}</span>
                </div>
                <file-uploader
                  :data="item.fileList"
                  :file-type="item.fileTypeName"
                  :config-attachment-id="item.id"
                  :limit="20"
                  @remove="removeFile"
                  @upload-success="uploadSuccessFile"
                />
              </div>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

    </div>
    <!-- -----------------设计申请 -->
    <div v-if="onlyStore" class="mt20">
      <div class="qup-title-box">
        <span class="border" /><span>设计申请</span>
      </div>
      <el-form ref="designForm" :rules="formRules" :model="formData.shopDesignDTO" size="mini" label-width="150px">
        <el-row class="form_item_height">
          <el-col :xs="12" :sm="12" :md="8" :lg="6" :xl="6">
            <el-form-item label="门头报图面积:" prop="doorHeadPicArea" :rules="[{ required: true, message: '请输入门头报图面积' }]">
              <el-input v-model.number="formData.shopDesignDTO.doorHeadPicArea" />
            </el-form-item>
          </el-col>
          <el-col :xs="12" :sm="12" :md="8" :lg="6" :xl="6">
            <el-form-item label="是否KA卖场:" prop="isKaMarket" required>
              <el-select
                v-model="formData.shopDesignDTO.isKaMarket"
                placeholder="请选择"
                style="width: 100%"
                @change="handleChange"
              >
                <el-option
                  v-for="item in booleansList"
                  :key="item.dictCode"
                  :label="item.dictName"
                  :value="item.dictCode"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :xs="12" :sm="12" :md="8" :lg="6" :xl="6">
            <el-form-item label="门头模式:" prop="doorHeadMode">
              <el-select
                v-model="formData.shopDesignDTO.doorHeadMode"
                placeholder="请选择"
                style="width: 100%"
                @change="handleChange"
              >
                <el-option
                  v-for="item in doorHeadModeList"
                  :key="item.dictCode"
                  :label="item.dictName"
                  :value="item.dictCode"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :xs="12" :sm="12" :md="8" :lg="6" :xl="6">
            <el-form-item label="门头设计内容:" prop="doorHeadDesignArr">
              <el-select
                v-model="formData.shopDesignDTO.doorHeadDesignArr"
                multiple
                placeholder="请选择"
                style="width: 100%"
                @change="handleChange"
              >
                <el-option
                  v-for="item in doorHeadDesignAll"
                  :key="item.dictCode"
                  :label="item.dictName"
                  :value="item.dictCode"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :xs="12" :sm="12" :md="8" :lg="6" :xl="6">
            <el-form-item label="入口门类型:" prop="entranceType">
              <el-select
                v-model="formData.shopDesignDTO.entranceType"
                placeholder="请选择"
                style="width: 100%"
                @change="handleChange"
              >
                <el-option
                  v-for="item in entranceTypeAll"
                  :key="item.dictCode"
                  :label="item.dictName"
                  :value="item.dictCode"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :xs="12" :sm="12" :md="8" :lg="6" :xl="6">
            <el-form-item label="是否需要门头效果图:" prop="isNeedRendering" required>
              <el-select
                v-model="formData.shopDesignDTO.isNeedRendering"
                placeholder="请选择"
                style="width: 100%"
                @change="handleChange"
              >
                <el-option
                  v-for="item in booleansList"
                  :key="item.dictCode"
                  :label="item.dictName"
                  :value="item.dictCode"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :xs="12" :sm="12" :md="8" :lg="6" :xl="6">
            <el-form-item label="预计装修进场时间:" prop="expectRenovationTime" required>
              <el-date-picker
                v-model="formData.shopDesignDTO.expectRenovationTime"
                value-format="yyyy-MM-dd HH:mm:ss"
                align="right"
                type="datetime"
                placeholder="选择日期"
                :picker-options="pickerOptions"
              />
            </el-form-item>
          </el-col>
          <el-col :xs="12" :sm="12" :md="8" :lg="6" :xl="6">
            <el-form-item label="预计开业时间:" prop="expectOpenTime" required>
              <el-date-picker
                v-model="formData.shopDesignDTO.expectOpenTime"
                value-format="yyyy-MM-dd HH:mm:ss"
                align="right"
                type="datetime"
                placeholder="选择日期"
                :picker-options="pickerOptions"
              />
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
            <el-form-item label="申请说明:" prop="applyDesc">
              <el-input v-model="formData.shopDesignDTO.applyDesc" maxlength="300" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div class="qup-title-box">
        <span class="border" /><span>附件信息</span>
      </div>
      <!-- 列表 -->
      <div>
        <el-button size="mini" type="primary" @click.native="handleAddFile">新增</el-button>
        <el-button size="mini" type="primary" @click="handleDelete">删除</el-button>
        <file-detail
          type="selection"
          style="margin-top:20px"
          :file-data="fileDataList"
          @select="getSelectData"
        />
        <file-add-dlg v-if="showFileAdd" ref="formDlg" :visible.sync="showFileAdd" @success="onSuccess" />
      </div>
    </div>
  </div>
</template>

<script>
// import imgUpload from '../../components/ImgUploader/ImgUploader'  图片上传组件
// import EnclosureForm from './EnclosureForm'
import { getDictByPatchType } from '@/api/dataDict'
import { submitEditShopData } from '@/api/storeConstruction'
import fileUploader from '@/components/importFile'
import { postConfigAttachmentTemplate } from '@/api/proConfig'
// import { getShopAttachment } from '@/api/decorate'
import { getUserInfo } from '@/utils/auth'
import FileDetail from '../../storeMapping/components/fileDetail.vue'
import FileAddDlg from './component/fileAddDlg.vue'
import { taskValide, searchCustomer } from '@/api/common.js'
import { searchConstCode, saveMapData } from '@/api/shopMap'
export default {
  name: 'NewEditor',
  components: { fileUploader, FileDetail, FileAddDlg },
  // components: {
  //   imgUpload
  // },
  props: {
    pageShow: {
      type: Boolean,
      default: false,
      required: true
    },
    detailData: {
      type: [String, Object],
      default: ''
    },
    typeFlag: {
      type: String,
      default: 'add'
    },
    stateList: {
      type: Array,
      default: () => []
    }
  },
  data() {
    return {
      // --------------------------测绘
      fileTypeList: [],
      fileData: [],
      fileDataList: [],
      fileList: [],
      loading: false,
      showFileAdd: false,
      // 图片上传字段
      dialogImageUrl: '',
      dialogVisible: false,
      disabled: false,
      hasMarket: false,
      hasDoor: false,
      hasExtend: false,
      hasRenovate: false,
      onlyStore: false,
      checked1: false,
      checked2: false,
      marketTypeList: [], // 报图类型
      constTypeList: [], // 门店建设类型
      typeList: [], // 门店建设类型
      bizmanTypeList: [], // 商家类别
      decorationFormList: [], valued: [], // 装修形式
      decorationRangeList: [], // 门店建设范围
      booleansList: [], // 判断是否
      booleansIntList: [
        { dictCode: 1, dictName: '是' },
        { dictCode: 0, dictName: '否' }
      ], // 判断是否
      cityLevelList: [], // 城市级别
      shopTypeList: [], // 门店类型
      bizTypeList: [], // 门店业务类型
      businessStatusList: [], // 门店营业状态
      applyCategoryList: [
        { dictCode: 'A', dictName: '测绘申请' },
        { dictCode: 'B', dictName: '设计申请' }
      ],
      // --------------------------设计
      // 是否KA卖场 KaType
      KaType: [],
      // 门头模式
      doorHeadModeList: [],
      // 独立店门头设计内容
      doorHeadDesignList: [],
      doorHeadDesignAll: [],
      // 入口门类型
      entranceTypeList: [],
      entranceTypeAll: [],
      // 预计报图业务类型
      expectPicTypeList: [],
      // -----------------设计结束
      num: 1, // 默认数量
      isAdd: true,
      index: '',
      oldItems: [], // 编辑时table值
      listByBizCodeList: [], // 价格类型列表
      pricingTypeCodeList: [], // 定价类别
      multipleSelection: [],
      singleSelection: [],
      priceTypeCodeList: [],
      selectDecorationForm: [],
      selectDecorationRange: [],
      shopConstructDTO: {},
      shopType: '',
      shopBizType: '',
      shopCityLevel: '',
      formData: {
        shop: [], // 门店
        // picUrl: '', // 图片
        // items: [],
        reportPicZoneArr: [],
        selectRange: [],
        decorationRange: [],
        shopSurveyDTO: {},
        shopDesignDTO: {},
        selectDecorationForm: []
      },
      formRules: {
        shop: [
          { required: true, message: '请选择门店' }
        ], // 门店
        marketType: [
          { required: true, message: '请选择报图类型' }
        ], // 报图类型
        constType: [
          { required: true, message: '请选择门店类型' }
        ], // 门店类型
        selectDecorationForm: [
          { required: true, message: '请选择装修形式' }
        ], // 装修形式
        selectRange: [
          { required: true, message: '请选择门店建设范围', trigger: 'change' }
        ], // 门店建设范围
        // 测绘
        applyShopTotalArea: [
          { required: true, message: '请输入测绘申请卖场总面积' }
        ], // 测绘申请卖场总面积
        refurbishArea: [
          { required: true, message: '请输入翻新面积' }
        ], // 翻新面积
        expansionArea: [
          { required: true, message: '请输入扩建面积' }
        ], // 扩建面积
        reportPicZoneArr: [
          { required: true, message: '请选择预计报图业务类型' }
        ], // 预计报图业务类型
        isShopRemove: [
          { required: true, message: '请选择卖场是否已拆除' }
        ], // 卖场是否已拆除
        unremoveReason: [
          { message: '请输入卖场未拆除原因' }
        ], // 卖场未拆除原因
        applyDesc: [
          { required: true, message: '请填写测绘申请说明', trigger: 'change' }
        ],
        // 设计
        isKaMarket: [
          { required: true, message: '请选择是否KA卖场' }
        ], // 是否KA卖场
        // doorHeadMode: [
        //   { required: true, message: '请选择门头模式' }
        // ], // 门头模式
        // doorHeadDesignArr: [
        //   { message: '请选择独立店门头设计内容' }
        // ], // 独立店门头设计内容
        // entranceType: [
        //   { required: true, message: '请选择入口门类型' }
        // ], // 入口门类型
        isNeedRendering: [
          { required: true, message: '请选择是否需要门头效果图' }
        ], // 是否需要门头效果图
        expectRenovationTime: [
          { required: true, message: '请选择预计装修进场时间' }
        ], // 预计装修进场时间
        expectOpenTime: [
          { required: true, message: '请选择预计开业时间' }
        ] // 预计开业时间
      },
      pickerOptions: {
        disabledDate(time) {
          var date = new Date()
          var y = date.getFullYear()
          var m = date.getMonth() + 1
          var d = date.getDate()
          var nowTime = new Date(`${y}-${m}-${d} 00:00:00`)
          return time.getTime() < nowTime.getTime()
        }
      },
      checkList: [], // 门店建设范围
      // 门店
      shopDialogConfig: {
        title: '门店',
        interfacePath: `/select-service/api/v1/shop/page`,
        setting: [
          {
            prop: 'code',
            title: '门店编码'
          },
          {
            prop: 'name',
            title: '门店名称'
          }
        ]
      },
      areaConfig: {
        title: '预计报图区域',
        interfacePath: `${process.env.VUE_APP_BASE_API}/api/v1/configArea/page`,
        setting: [
          {
            prop: 'areaCode',
            title: '编码'
          },
          {
            prop: 'areaName',
            title: '名称'
          }
        ],
        filtersRaw: [{ 'id': 'enable', 'property': 'enable', 'operator': '=', 'value': 1 }]
      },
      formDataS: [],
      // items: [],
      btnList: [], // 按钮权限
      les: ``,
      interfacePath: `` // 调公共接口
    }
  },
  computed: {
    selectedFileIds() {
      return this.fileList.map(row => {
        return row.id
      })
    },
    nowvisible: {
      get() {
        return this.visible
      },
      set(val) {
        this.$emit('update:visible', val)
      }
    }
  },

  created() {
    this.getDictByPatchTypeAll(['SHOP_TYPE', 'CITY_LEVEL', 'BOOLEANS',
      'MARKET_TYPE', 'CONST_TYPE', 'BIZMAN_TYPE', 'DECORATION_FORM',
      'DECORATION_RANGE', 'BELONG_REGION', 'DOOR_HEAD_MODE',
      'DOOR_HEAD_DESIGN', 'ENTRANCE_TYPE', 'BIZ_TYPE', 'SHOP_BIZ_STATE'])
      .then(res => {
        this.booleansList = res.BOOLEANS // 是否
        this.marketTypeList = res.MARKET_TYPE // 市场层级
        this.constTypeList = res.CONST_TYPE // 门店建设类型
        // this.newTypeList = res.CONST_TYPE.filter(item => item.includes('MARKET'))
        // this.renovateTypeList = res.CONST_TYPE.filter(item => !item.includes('MARKET'))
        this.bizmanTypeList = res.BIZMAN_TYPE // 商家类型
        this.decorationFormList = res.DECORATION_FORM // 装修形式
        this.expectPicTypeList = res.BELONG_REGION // 区域
        this.decorationRangeList = res.DECORATION_RANGE // 装修范围
        this.cityLevelList = res.CITY_LEVEL // 城市级别
        this.shopTypeList = res.SHOP_TYPE // 门店类型
        this.doorHeadModeList = res.DOOR_HEAD_MODE // 门头模式
        this.doorHeadDesignAll = res.DOOR_HEAD_DESIGN // 门头设计类型
        this.entranceTypeAll = res.ENTRANCE_TYPE // 入口门设计类型
        this.bizTypeList = res.BIZ_TYPE // 门店业务类型
        this.businessStatusList = res.SHOP_BIZ_STATE // 门店营业状态
      })
  },
  methods: {
    convertDataFormat(str) {
      if (!str || !str.length) return []
      const arr = str.split(',')
      return arr
    },
    // // 获取附件
    // getFiles() {
    //   getShopAttachment(this.id).then(res => {
    //     this.fileTypeList.forEach(row => {
    //       row.fileList = res.data.filter(i => i.configAttachmentId === row.id)
    //     })
    //   })
    // },
    getFileType(modelCode) {
      postConfigAttachmentTemplate(modelCode).then(res => {
        if (res.success === 1) {
        // 根据modelId获取每个配置id
          let model = ''
          if (modelCode === 'SHOP_SURVEY') {
            model = '卖场内部大场景照片'
          }
          this.fileTypeList = res.data.records.filter(item => item.attachmentType === model)
          this.fileTypeList.forEach(row => {
            this.$set(row, 'fileList', [])
          })
        }
      })
    },
    // 勾选的附件数据
    getSelectData(data) {
      if (data) {
        this.fileList = data
      }
    },
    // 新增附件
    onSuccess(data) {
      this.fileDataList = [...this.fileDataList, ...data]
      this.refreshFileData()
    },
    // 新增附件上传
    handleAddFile() {
      this.showFileAdd = true
    },
    // 删除附件
    handleDelete() {
      if (!this.singleJudge(this.selectedFileIds, '删除文件', false)) {
        return
      }

      this.$confirm(`是否确认删除数据?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.fileDataList.forEach((row, index) => {
          this.selectedFileIds.forEach(i => {
            if (row.id === i) {
              row.dr = 1
            }
          })
        })
        const fileList = this.fileDataList.filter(item => !item.dr)
        this.fileDataList = fileList
      }).catch(() => {})
    },
    refreshFileData() {
      // 重新请求接口获取附件信息
    },
    removeFile() {},
    uploadSuccessFile() {},
    async getDictByPatchTypeAll(data) {
      const obj = await getDictByPatchType(data)
        .then(res => {
          return res
        })
      return obj
    },
    // 切换门店
    async handleChangeShop(data) {
      this.loading = true
      // 验证当前选择门店是否有测绘任务
      if (!this.onlyStore && this.hasMarket) {
        const isValid = await taskValide({ shopCode: data[0].code })
        if (isValid.code) {
          this.formData.shop = [{ code: '', name: '' }]
          this.clearFormConst()
          this.$message.warning(isValid.msg)
          return
        }
        await searchConstCode(data[0].code).then(res => {
          if (res.success && res.data && res.data.records && res.data.records.length > 0) {
            this.formData.constCode = res.data.records[0].constCode
            this.$set(this.formData, 'marketType', res.data.records[0].marketType)
            this.$set(this.formData, 'bizmanType', res.data.records[0].bizmanType)
            this.changeMarketType(res.data.records[0].marketType)
            this.changeConstType(res.data.records[0].constType)
            this.$set(this.formData, 'constType', res.data.records[0].constType)
            this.$set(this.formData, 'selectDecorationForm', this.convertDataFormat(res.data.records[0].decorationForm))
            if (res.data.records[0].dataSource === 'A') {
              this.disabled = true
            }
            // this.formData.marketType = res.data.records[0].marketType
            // this.formData.constType = res.data.records[0].constType
            // this.formData.bizmanType = res.data.records[0].bizmanType
          }
        }).catch(() => {
          this.loading = false
        })
        // return
      }
      // 根据门店下的客户code查询 对应的经销商信息
      await searchCustomer(data[0].customerCode, 'storemapping').then(res => {
        if (res.success === 1 && res.data.records.length > 0) {
          this.shopConstructDTO = res.data
          this.formData.customerName = res.data.records[0].contactName// 经销商
          this.formData.customerPhone = res.data.records[0].contactPhone// 经销商电话
        }
      }).catch(() => {
        this.loading = false
      })
      // if (this.onlyStore) {
      this.$set(this.formData, 'shopMarketLevel', data[0].marketLevelCode)
      this.$set(this.formData, 'shopArea', data[0].operateArea)
      this.$set(this.formData, 'shopCode', data[0].code)
      this.$set(this.formData, 'shopName', data[0].name)
      this.$set(this.formData, 'clientName', data[0].customerName)
      this.$set(this.formData, 'clientCode', data[0].customerCode)
      // this.$set(this.formData, 'customerPhone', data[0].customerPhone)
      this.$set(this.formData, 'officeName', data[0].agencyName)
      this.$set(this.formData, 'officeCode', data[0].agencyCode)
      this.$set(this, 'shopType', this.formaterData(this.shopTypeList, data[0].shopClassify))
      this.$set(this.formData, 'shopType', data[0].shopClassify)
      this.$set(this.formData, 'shopBizType', data[0].businessType)
      this.$set(this, 'shopBizType', data[0].businessTypeName)
      this.$set(this, 'shopCityLevel', this.formaterData(this.cityLevelList, data[0].cityLevel))
      this.$set(this.formData, 'shopCityLevel', data[0].cityLevel)
      this.$set(this.formData, 'businessStatus', data[0].businessStatus)
      this.$set(this.formData, 'shopAddress', data[0].shopAddr)
      // }
      this.$forceUpdate()
      if (this.formData.shopType === '1') {
        this.doorHeadDesignList = this.doorHeadDesignAll.filter(item => item.dictCode === 'LED_DISPLAY')
        this.entranceTypeList = this.entranceTypeAll.filter(item => item.dictCode === 'SHOP_IN_SHOP' || item.dictCode === 'NO_DESIGN')
      } else {
        this.doorHeadDesignList = this.doorHeadDesignAll
        this.entranceTypeList = this.entranceTypeAll.filter(item => item.dictCode !== 'SHOP_IN_SHOP' && item.dictCode !== 'NO_DESIGN')
      }
      this.loading = false
    },
    clearFormConst() {
      this.formData.shop = []// 门店编码
      this.formData.shopCode = ''// 门店编码
      this.formData.shopName = ''// 门店名称
      this.formData.shopMarketLevel = ''
      this.shopBizType = ''// 门店业务类型
      this.formData.shopBizType = ''// 门店业务类型
      this.formData.constCode = ''// 门店建设项目号
      this.formData.clientName = ''// 所属客户
      this.formData.clientCode = ''// 所属客户
      this.formData.officeCode = ''// 所属办事处
      this.formData.officeName = ''// 所属办事处
      this.formData.shopType = ''// 门店类型
      this.shopType = ''// 门店类型
      this.formData.customerName = ''// 经销商
      this.formData.customerPhone = ''// 经销商电话
      this.formData.shopCityLevel = ''// 门店城市级别
      this.shopCityLevel = ''// 门店城市级别
      this.formData.shopAddress = ''// 门店详细地址
      this.formData.shopArea = ''// 门店面积
      this.formData.businessStatus = ''// 门店营业状态
      this.$set(this.formData, 'marketType', '')
      this.$set(this.formData, 'constType', '')
      this.$set(this.formData, 'bizmanType', '')
      this.$set(this.formData, 'selectDecorationForm', [])
      this.loading = false
    },
    // 格式化数据
    formaterData(arr, dictCode) {
      const tmpArr = arr.filter(item => item.dictCode === dictCode)
      if (tmpArr.length) {
        return tmpArr[0].dictName
      }
      return dictCode
    },
    // 切换装修形式
    changeDecorationForm(data) {
      this.formData.decorationForm = data.toString()
    },
    formaterArr(data, str) {
      if (!str || !str.length) return
      let list = []
      if (typeof (str) === 'string') {
        list = str.split(',')
      } else {
        list = str
      }
      const arr = []
      data.forEach((item) => {
        const flag = list.some(v => v === item.dictCode)
        if (flag) {
          arr.push(item.dictName)
        }
      })
      return arr.toString()
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url
      this.dialogVisible = true
    },
    handleSelectionChange(val) {
      this.multipleSelection = val
    },
    // 选择区域
    areaChange(row) {
      if (row && row.length) {
        const arr = row.map(item => { return item.areaCode })
        this.formData.shopSurveyDTO.reportPicZone = arr.join(',')
      }
    },
    // 删除行
    delRow() {
      if (this.multipleSelection.length < 1) {
        this.$message.warning(`请选择【删除】项`)
        return false
      }
      this.$confirm('是否确认删除所选内容?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const mulSelect = this.multipleSelection
        const data = this.formData.items
        this.deleteData = data.filter((item) => {
          const arrlist = mulSelect.map((v) => v.id)
          return arrlist.includes(item.id)
        })
        const newData = data.filter((item) => {
          const arrlist = mulSelect.map((v) => v.calculateStep)
          return !arrlist.includes(item.calculateStep)
        })
        this.$set(this.formData, 'items', newData)
        this.$forceUpdate()
      })
    },
    goBack() {
      this.$confirm('此操作不可逆，是否确认并返回列表界面?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.nowvisible = false
        this.pageShow = false
        // this.$refs.refForm.clearValidate()
        this.$emit('goBack', this.pageShow)
      })
    },
    // 提交表单处理
    submitForm() {
      this.$refs['refForm'].validate((valid) => {
        if (valid) {
          this.formData.decorationRange = this.formData.selectRange.toString()
          if (this.onlyStore) {
            this.$refs['designForm'].validate((valid) => {
              if (valid) {
                if (!this.fileDataList.length) {
                  this.$message.warning('请上传附件')
                  return
                }
                this.formData.shopDesignDTO.shopAttachmentDTOList = this.fileDataList
                this.formData.expectOpenTime = this.formData.shopDesignDTO.expectOpenTime
                this.formData.decorationForm = this.formData.selectDecorationForm.toString()
                this.formData.shopDesignDTO.doorHeadDesign = this.formData.shopDesignDTO.doorHeadDesignArr.toString()
                this.loading = true
                submitEditShopData(this.formData).then(res => {
                  if (res.success) {
                    this.nowvisible = false
                    this.pageShow = false
                    this.$refs.refForm.clearValidate()
                    this.$emit('goBack', this.pageShow)
                  }
                  this.loading = false
                }).catch(() => {
                  this.loading = false
                })
              }
            })
          } else if (this.hasMarket) {
            this.$refs['surveyForm'].validate((valid) => {
              if (valid) {
                let fileArr = []
                const len = this.fileTypeList.map(item => item.fileList.length)
                if (!len[0]) {
                  this.$message.warning('请上传附件')
                  return
                }
                if (len[0] < 5) {
                  this.$message.warning('请上传不少于5张图片')
                  return
                }
                const arr = this.fileTypeList.map(item => item.fileList)
                fileArr = arr.flat(Infinity)
                fileArr.forEach(item => {
                  item.modelId = this.id
                })
                // changeFileList(fileArr).then(res => {
                //   if (res.success) {
                this.formData.shopSurveyDTO.shopAttachmentDTOList = fileArr
                // this.formData.shopSurveyDTO.reportPicZone = this.formData.shopSurveyDTO.reportPicZone.toString()
                const data = {
                  shopCode: this.formData.shopCode, // 门店编码
                  shopName: this.formData.shopName, // 门店名称
                  shopMarketLevel: this.formData.shopMarketLevel,
                  shopBizType: this.formData.shopBizType, // 门店业务类型
                  constCode: this.formData.constCode, // 门店建设项目号
                  clientName: this.formData.clientName, // 所属客户
                  clientCode: this.formData.clientCode, // 所属客户
                  officeCode: this.formData.officeCode, // 所属办事处
                  officeName: this.formData.officeName, // 所属办事处
                  shopType: this.formData.shopType, // 门店类型
                  customerName: this.formData.customerName, // 经销商
                  customerPhone: this.formData.customerPhone, // 经销商电话
                  shopCityLevel: this.formData.shopCityLevel, // 门店城市级别
                  businessStatus: this.formData.businessStatus, // 门店营业状态
                  shopAddress: this.formData.shopAddress, // 门店详细地址
                  decorationRange: this.formData.decorationRange,
                  marketType: this.formData.marketType,
                  constType: this.formData.constType,
                  bizmanType: this.formData.bizmanType,
                  decorationForm: this.formData.selectDecorationForm.toString()
                }
                const obj = { ...data }
                obj.shopConstructDTO = data
                obj.shopConstructDTO.marketType = this.formData.marketType
                obj.shopConstructDTO.constType = this.formData.constType
                obj.shopConstructDTO.bizmanType = this.formData.bizmanType
                obj.shopConstructDTO.decorationForm = this.formData.selectDecorationForm.toString()
                obj.shopConstructDTO.decorationRange = this.formData.decorationRange
                this.formData.shopSurveyDTO.dataSource = 'ARTIFICIAL'
                const form = { ...obj, ...this.formData.shopSurveyDTO }
                // return
                delete form.reportPicZoneArr
                if (this.formData.constCode && this.formData.constCode.length) {
                  this.$confirm('检测到当前门店还有未完结的门店建设项目号，不能执行新增操作，是否在原项目号下新增测绘任务？', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                  }).then(() => {
                    this.loading = true
                    // this.formData.isCheckSurvey = 0
                    saveMapData(form, 2).then(res => {
                      if (res.success) {
                        this.nowvisible = false
                        this.pageShow = false
                        this.$refs.refForm.clearValidate()
                        this.$emit('goBack', this.pageShow)
                      }
                      this.loading = false
                    }).catch(() => {
                      this.loading = false
                    })
                  })
                  return
                }
                this.loading = true
                delete form.constCode
                saveMapData(form, 2).then(res => {
                  if (res.success) {
                    this.nowvisible = false
                    this.pageShow = false
                    this.$refs.refForm.clearValidate()
                    this.$emit('goBack', this.pageShow)
                  }
                  this.loading = false
                }).catch(() => {
                  this.loading = false
                })
                // submitEditShopData(this.formData).then(res => {
                //   if (res.success) {
                //     if (res.msg && res.msg.length) {
                //       this.$confirm(`${res.msg}`, '提示', {
                //         confirmButtonText: '确定',
                //         cancelButtonText: '取消',
                //         type: 'warning'
                //       }).then(() => {
                //         this.formData.isCheckSurvey = 0
                //         submitEditShopData(this.formData).then(res => {
                //           if (res.success) {
                //             this.nowvisible = false
                //             this.pageShow = false
                //             this.$refs.refForm.clearValidate()
                //             this.$emit('goBack', this.pageShow)
                //           }
                //         })
                //       })
                //       return
                //     }
                //     this.nowvisible = false
                //     this.pageShow = false
                //     this.$refs.refForm.clearValidate()
                //     this.$emit('goBack', this.pageShow)
                //   }
                // })
                //   }
                // })
              }
            })
          }
        }
      })
      // wholesalePricingSave(arr).then(res => {
      //   if (res.success === 1) {
      //     this.$message.success('保存成功')
      //     this.$emit('refreshTable')
      //   }
      // })
    },
    // 改变所属定价类别的值
    // changePri(row) {
    //   row.priceTypeCode = ''
    //   row.priceTypeName = ''
    //   row.priceType = []

    //   const filtersRaw = [{ id: 'dr', property: 'dr', value: '0', operator: '=' }]
    //   if (row.pricingTypeCode) {
    //     const newFiltersRaw = filtersRaw.concat({ id: 'pricingTypeCode', property: 'pricingTypeCode', value: row.pricingTypeCode, operator: '=' })
    //     this.$set(row, 'filtersRaw', newFiltersRaw)
    //   } else {
    //     this.$set(row, 'filtersRaw', filtersRaw)
    //   }
    // },
    selectionChange(val) {
      this.singleSelection = val
    },
    // 选择：
    // changePriceType(row) {
    //   if (row && row.priceType && row.priceType.length > 0) {
    //     const data = row.priceType
    //     row.priceTypeCode = data ? data[0].priceTypeCode : row.priceTypeCode
    //     row.priceTypeName = data ? data[0].priceTypeName : row.priceTypeName
    //     row.priceTypeId = data ? data[0].id : row.priceTypeId
    //     row.calculateModelCode = data ? data[0].calculateModelCode : row.calculateModelCode
    //   } else {
    //     row.priceTypeCode = ''
    //     row.priceTypeName = ''
    //   }
    // },
    // standardCode', title: '价格类型编码' }, { prop: 'standardName

    // 按钮组
    btnOperate(flag) {
      switch (flag) {
        case 'add':
          this.addRow()
          break
        case 'del':
          this.delRow()
          break
        default:
          break
      }
    },
    // 报图类型切换
    changeMarketType(data) {
      this.$set(this.formData, 'constType', '')
      if (data === 'NEW_MARKET') {
        // this.formRules.bizmanType = [{ required: true, message: '请选择商家类别' }]
        this.typeList = this.constTypeList.filter(item => item.dictCode.indexOf('MARKET') !== -1)
      } else {
        // this.formRules.bizmanType = [{ required: false, message: '请选择商家类别' }]
        this.typeList = this.constTypeList.filter(item => item.dictCode.indexOf('MARKET') === -1)
      }
      this.$nextTick(() => {
        this.$refs.refForm.clearValidate()
      })
    },
    // 选择门店建设类型
    changeConstType(data) {
      if (data.indexOf('EXTEND') !== -1 && data.indexOf('RENOVATE') !== -1) {
        this.hasExtend = true
        this.hasRenovate = true
      } else if (data.indexOf('EXTEND') === -1 && data.indexOf('RENOVATE') !== -1) {
        this.hasRenovate = true
        this.hasExtend = false
      } else if (data.indexOf('EXTEND') !== -1 && data.indexOf('RENOVATE') === -1) {
        this.hasRenovate = false
        this.hasExtend = true
      } else {
        this.hasExtend = false
        this.hasRenovate = false
      }
    },
    // 切换门店建设范围
    async handleCheckAllChange(value) {
      this.clearFormConst()
      // this.formData.decorationRange = value.toString()
      if (!value.length || !value) {
        this.formData.applyCategory = ''
        this.onlyStore = false
        this.hasMarket = false
        return
      }
      const flag = value.some(v => v === 'STORES')
      const flag1 = value.some(v => v === 'DOOR')
      if (flag1) {
        this.hasDoor = true
      } else {
        this.hasDoor = false
      }
      if (flag) {
        this.onlyStore = false
        this.hasMarket = true
        this.formData.applyCategory = 'A'
        this.formData.shopDesignDTO = {
          doorHeadDesignArr: []
        }
        const { userName } = getUserInfo()
        this.formData.shopSurveyDTO.applicantName = userName
        this.$set(this.formData, 'selectDecorationForm', [])
        // this.formData.selectDecorationForm = []
        const date = new Date()
        const y = date.getFullYear()
        const m = this.formaterDate(date.getMonth() + 1)
        const d = this.formaterDate(date.getDate())
        const hh = this.formaterDate(date.getHours())
        const mm = this.formaterDate(date.getMinutes())
        const ss = this.formaterDate(date.getSeconds())
        this.formData.shopSurveyDTO.applyTime = `${y}-${m}-${d} ${hh}:${mm}:${ss}`
        this.getFileType('SHOP_SURVEY')
        this.$nextTick(() => {
          this.$refs.refForm.clearValidate()
          this.$refs.surveyForm.clearValidate()
        })
        // setTimeout(() => {
        //   this.$refs.surveyForm.clearValidate()
        // }, 0)
      } else {
        this.hasMarket = false
        this.onlyStore = true
        this.formData.applyCategory = 'B'
        this.formData.shopSurveyDTO = {
          reportPicZoneArr: []
        }
        this.formData.selectDecorationForm = ['PACKAGE']
        // this.disabled = true
        await this.getFileType('SHOP_DESIGN')
        this.$nextTick(() => {
          this.$refs.refForm.clearValidate()
          this.$refs.designForm.clearValidate()
        })
      }
    },
    formaterDate(date) {
      if (date < 10) {
        return '0' + date
      }
      return date
    }

  }
}
</script>
<style lang='scss' scoped>
  /deep/ .el-breadcrumb__inner{
    color: $qup-color-primary;
  }
.img-upload-container {
  width: fit-content;
  display: flex;
  flex-wrap: wrap;
  justify-content: flex-end;
  align-items: center;
  .icon-msg{
    margin-left: 10px;
    color: #999;
  }
}
.subdaoch{margin: 10px 0;}
.but20{ margin-bottom: 20px;}
.el-breadcrumb__inner,.btn-green{
    color: #3DC094;
}
.qup-title-box{background: #f2f2f2; line-height: 30px;}
.showsj{
  display: block;
}
.initPage{
  display: none;
}
</style>
